package com.hb.advertising;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.kwad.sdk.api.KsAdSDK;
import com.kwad.sdk.api.KsInterstitialAd;
import com.kwad.sdk.api.KsLoadManager;
import com.kwad.sdk.api.KsRewardVideoAd;
import com.kwad.sdk.api.KsScene;
import com.kwad.sdk.api.KsSplashScreenAd;
import com.kwad.sdk.api.KsVideoPlayConfig;
import com.kwad.sdk.api.SdkConfig;
import com.qq.e.ads.banner2.UnifiedBannerADListener;
import com.qq.e.ads.banner2.UnifiedBannerView;
import com.qq.e.ads.cfg.MultiProcessFlag;
import com.qq.e.ads.interstitial2.UnifiedInterstitialAD;
import com.qq.e.ads.interstitial2.UnifiedInterstitialADListener;
import com.qq.e.ads.rewardvideo.RewardVideoAD;
import com.qq.e.ads.rewardvideo.RewardVideoADListener;
import com.qq.e.ads.splash.SplashAD;
import com.qq.e.ads.splash.SplashADListener;
import com.qq.e.comm.managers.GDTADManager;
import com.qq.e.comm.managers.GDTAdSdk;
import com.qq.e.comm.util.AdError;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.helpers.DefaultHandler;

import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private BridgeWebView webView;
    private ViewGroup frame;
    private TTNativeExpressAd mTTAd;
    private KsInterstitialAd mKsInterstitialAd;
    private boolean mIsLoaded;
    private int screenOrientation = SdkConfig.SCREEN_ORIENTATION_UNKNOWN;
    private KsRewardVideoAd mRewardVideoAd;
    private ViewGroup banner;
    private TTNativeExpressAd ad;
    private int type;
    private String provider;
    private String id;
    private String callname;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        frame = findViewById(R.id.frame_layout);
        banner = findViewById(R.id.banner);
        TTAdManager ttAdManager = TTAdSdk.getAdManager();
        ttAdManager.requestPermissionIfNecessary(this);
        KsAdSDK.init(this, new SdkConfig.Builder()
                .appId("618800004") // 测试aapId，请联系快⼿平台申请正式AppId，必填
                .showNotification(true) // 是否展示下载通知栏
                .debug(true) // 是否开启sdk 调试⽇志 可选
                .build());
        TTAdManagerHolder.init(this);
        MultiProcessFlag.setMultiProcess(true);
        UMConfigure.init(getApplicationContext(),"60f67609999517176d5e0e7f","movie",UMConfigure.DEVICE_TYPE_PHONE,"");
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        GDTAdSdk.init(this, "1200018052");
        frame.setVisibility(View.VISIBLE);
        initView();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==1){
                playAD(JsonString);
            }else {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri targetUrl = Uri.parse(url);
                intent.setData(targetUrl);
                startActivity(intent);
            }

        }
    };
    private String JsonString;
    @JavascriptInterface
    public void postMessage(String JSONString){
        this.JsonString=JSONString;
        Log.e(TAG, "postMessage: "+JSONString );
        Message message = mHandler.obtainMessage();
        message.what = 1;
        mHandler.sendMessage(message);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }



    private void initView() {
        webView = (BridgeWebView) findViewById(R.id.web_view);
        webView.setWebContentsDebuggingEnabled(true);
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                return false;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url,
                                       String message, JsResult result) {
                // TODO Auto-generated method stub
                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message,
                                      String defaultValue, JsPromptResult result) {
                // TODO Auto-generated method stub
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
        });
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.supportMultipleWindows();
        settings.setAllowContentAccess(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSavePassword(true);
        settings.setSaveFormData(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setLoadsImagesAutomatically(true);
        webView.setWebViewClient(webViewClient);
                //建立js和Android的桥梁
        webView.addJavascriptInterface(this, "hbCallHandler");
        webView.loadUrl("http://mv.aiyouxiba.com/");
    }

    private WebViewClient webViewClient=new WebViewClient(){
        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成

        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return false;
        }

    };

    public void openUrl(String JSONString) {
        try {
            JSONObject object = new JSONObject(JSONString);
            JSONObject data = object.getJSONObject("data");
            url = data.getString("url");
            Message message = mHandler.obtainMessage();
            message.what = 2;
            mHandler.sendMessage(message);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private List<DataBean> BannerList=new ArrayList<>();
    private List<DataBean> list=new ArrayList<>();
    private List<DataBean> RewardList=new ArrayList<>();
    private int Rewardposition=0;
    private int Bannerposition=0;





    public void playAD(String JSONString) {
        Rewardposition=0;
        Bannerposition=0;
        position=0;
        list.clear();
        BannerList.clear();
        RewardList.clear();
        try {
            JSONObject object = new JSONObject(JSONString);
            String apiname = object.getString("apiname");
            if (apiname.equals("open")){
                openUrl(JSONString);
                return;
            }
            JSONObject data = object.getJSONObject("data");
            callname = object.getString("callname");
            JSONArray ads = data.getJSONArray("ads");
            for (int i = 0; i < ads.length(); i++) {
                JSONObject jsonObject = ads.getJSONObject(i);
                type = jsonObject.getInt("type");
                provider = jsonObject.getString("provider");
                id = jsonObject.getString("id");
                if (type==1){
                    list.add(new DataBean(provider,type,id));
                }else if (type==4){
                    BannerList.add(new DataBean(provider,type,id));
                }else if (type==3){
                    RewardList.add(new DataBean(provider,type,id));
                }
            }
            switch (type) {
                case 1:
                    Log.e(TAG, "playAD: "+list.get(position).getProvider() );
                    SplashAD(list.get(0).getProvider(), list.get(0).getId());
                    break;
                case 2:
                    InterstitialAD(provider, id);
                    break;
                case 3:
                    Log.e(TAG, "playAD: "+RewardList.get(0).getProvider() );
                    RewardVideoAD(RewardList.get(0).getProvider(), RewardList.get(0).getId());
                    break;
                case 4:
                    BannerAD(BannerList.get(0).getProvider(), BannerList.get(0).getId());
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    private int position=0;
    //开屏广告
    public void SplashAD(String provider, String codeId) {
        frame.setVisibility(View.VISIBLE);
        webView.setVisibility(View.INVISIBLE);
        switch (provider) {
            case "CSJ":
                TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(MainActivity.this);
                int width = MainActivity.this.getResources().getDisplayMetrics().widthPixels;
                int height = MainActivity.this.getResources().getDisplayMetrics().heightPixels;

                AdSlot adSlot = new AdSlot.Builder()
                        .setCodeId(codeId)
                        .setImageAcceptedSize(width, height)
                        .build();
                mTTAdNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
                    //请求广告失败
                    @Override
                    @MainThread
                    public void onError(int code, String message) {
                        //开发者处理跳转到APP主页面逻辑
                        Log.e(TAG, "onError: 穿山甲开屏"+message );
                        position++;
                        if (position>=list.size()-1){
                            webView.setVisibility(View.VISIBLE);
                            frame.setVisibility(View.GONE);
                            return;
                        }
                        SplashAD(list.get(position).getProvider(),list.get(position).getId());

                    }

                    //请求广告超时
                    @Override
                    @MainThread
                    public void onTimeout() {
                        //开发者处理跳转到APP主页面逻辑
                        position++;
                        if (position>=list.size()-1){
                            webView.setVisibility(View.VISIBLE);
                            frame.setVisibility(View.GONE);
                            return;
                        }
                        SplashAD(list.get(position).getProvider(),list.get(position).getId());

                    }

                    //请求广告成功
                    @Override
                    @MainThread
                    public void onSplashAdLoad(TTSplashAd ad) {
                        Log.e(TAG, "onSplashAdLoad: 请求成功");
                        if (ad == null) {
                            return;
                        }
                        //获取SplashView
                        View view = ad.getSplashView();
                        frame.removeAllViews();
                        //把SplashView 添加到ViewGroup中,注意开屏广告view：width =屏幕宽；height >=75%屏幕高
                        frame.addView(view);
                        //设置不开启开屏广告倒计时功能以及不显示跳过按钮,如果这么设置，您需要自定义倒计时逻辑
                        //ad.setNotAllowSdkCountdown();
                        ad.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {

                            //点击回调
                            @Override
                            public void onAdClicked(View view, int type) {

                            }

                            //展示回调
                            @Override
                            public void onAdShow(View view, int type) {
                                Log.e(TAG, "onAdShow: 展示");
                            }

                            //跳过回调
                            @Override
                            public void onAdSkip() {
                                //开发者处理跳转到APP主页面逻辑

                                frame.setVisibility(View.GONE);
                                webView.setVisibility(View.VISIBLE);
                                webView.loadUrl("javascript:window.hbJsBridge.invokeCalback('"+callname+"',true)");
                            }

                            //超时倒计时结束
                            @Override
                            public void onAdTimeOver() {
                                //开发者处理跳转到APP主页面逻辑
                                frame.setVisibility(View.GONE);
                                webView.setVisibility(View.VISIBLE);
                                webView.loadUrl("javascript:window.hbJsBridge.invokeCalback('"+callname+"',true)");
                            }
                        });

                    }
                }, 3000);
                break;
            case "KS":
                KsScene scene = new KsScene.Builder(Long.parseLong(codeId))
                        //是否需要开屏小窗展示，默认为false, 设置false后将不会回调 onShowMiniWindow
                        .needShowMiniWindow(true)
                        .build(); // 此为测试posId，请联系快手平台申请正式posId
                KsAdSDK.getLoadManager().loadSplashScreenAd(scene, new KsLoadManager.SplashScreenAdListener() {
                    @Override
                    public void onError(int code, String msg) {
                        Log.e(TAG, "onError: 快手开屏"+msg );
                        position++;
                        if (position>=list.size()-1){
                            webView.setVisibility(View.VISIBLE);
                            frame.setVisibility(View.GONE);
                            return;
                        }
                        SplashAD(list.get(position).getProvider(),list.get(position).getId());
                    }

                    @Override
                    public void onRequestResult(int adNumber) {

                    }

                    @Override
                    public void onSplashScreenAdLoad(@NonNull KsSplashScreenAd splashScreenAd) {
                        Fragment fragment = splashScreenAd.getFragment(new KsSplashScreenAd.SplashScreenAdInteractionListener() {
                            @Override
                            public void onAdClicked() {

                                frame.setVisibility(View.GONE);
                                webView.setVisibility(View.VISIBLE);
                                webView.loadUrl("javascript:window.hbJsBridge.invokeCalback('"+callname+"',true)");
                            }

                            @Override
                            public void onAdShowError(int code, String extra) {
                                position++;
                                if (position>=list.size()-1){
                                    webView.setVisibility(View.VISIBLE);
                                    frame.setVisibility(View.GONE);
                                    return;
                                }
                                SplashAD(list.get(position).getProvider(),list.get(position).getId());
                            }

                            @Override
                            public void onAdShowEnd() {

                                frame.setVisibility(View.GONE);
                                webView.setVisibility(View.VISIBLE);
                                webView.loadUrl("javascript:window.hbJsBridge.invokeCalback('"+callname+"',true)");
                            }

                            @Override
                            public void onAdShowStart() {
                            }

                            @Override
                            public void onSkippedAd() {
                                frame.setVisibility(View.GONE);
                                webView.setVisibility(View.VISIBLE);
                                webView.loadUrl("javascript:window.hbJsBridge.invokeCalback('"+callname+"',true)");
                            }
                        });
                        if (!isFinishing()) {
                            getSupportFragmentManager().beginTransaction()
                                    .replace(R.id.frame_layout, fragment)
                                    .commitAllowingStateLoss();
                        }
                    }
                });
                break;
            case "GDT":
                SplashAD ad = new SplashAD(this, codeId, new SplashADListener() {
                    @Override
                    public void onADDismissed() {

                        frame.setVisibility(View.GONE);
                        webView.setVisibility(View.VISIBLE);
                        webView.loadUrl("javascript:window.hbJsBridge.invokeCalback('"+callname+"',true)");
                    }

                    @Override
                    public void onNoAD(AdError adError) {
                        position++;
                        if (position>=list.size()-1){
                            webView.setVisibility(View.VISIBLE);
                            frame.setVisibility(View.GONE);
                            return;
                        }
                        SplashAD(list.get(position).getProvider(),list.get(position).getId());
                    }

                    @Override
                    public void onADPresent() {

                    }

                    @Override
                    public void onADClicked() {

                    }

                    @Override
                    public void onADTick(long l) {

                    }

                    @Override
                    public void onADExposure() {

                    }

                    @Override
                    public void onADLoaded(long l) {

                    }
                }, 0);
                ad.fetchAndShowIn(frame);
                break;
        }
    }

    //插屏广告
    public void InterstitialAD(String provider, String codeId) {
        switch (provider) {
            case "CSJ":
                TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(MainActivity.this);
                AdSlot adSlot = new AdSlot.Builder()
                        .setCodeId(codeId) //广告位id
                        .setSupportDeepLink(true)
                        .setAdCount(3) //请求广告数量为1到3条 //期望模板广告view的size,单位dp
                        .build();
                mTTAdNative.loadInteractionExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
                    //请求广告失败
                    @Override
                    public void onError(int code, String message) {
                        Log.e(TAG, "onError: 穿山甲插屏" + code + message);
                    }

                    //请求广告成功
                    @Override
                    public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                        if (ads == null || ads.size() == 0) {
                            return;
                        }
                        Log.e(TAG, "onSuccess: " + ads.size());
                        mTTAd = ads.get(1);
                        mTTAd.render();
                        mTTAd.setExpressInteractionListener(new TTNativeExpressAd.AdInteractionListener() {
                            @Override
                            public void onAdDismiss() {

                            }

                            @Override
                            public void onAdClicked(View view, int type) {

                            }


                            @Override
                            public void onAdShow(View view, int type) {
                                Log.d(TAG, "onAdShow");
                            }

                            @Override
                            public void onRenderFail(View view, String msg, int code) {
                                Log.d(TAG, "onRenderFail");
                            }

                            @Override
                            public void onRenderSuccess(View view, float width, float height) {
                                //返回view的宽高 单位 dp
                                Log.d(TAG, "onRenderSuccess");
                                mTTAd.showInteractionExpressAd(MainActivity.this);
                            }
                        });
                    }
                });
                break;
            case "KS":
                KsScene scene = new KsScene.Builder(Long.parseLong(codeId)).build();
                KsAdSDK.getLoadManager().loadInterstitialAd(scene,
                        new KsLoadManager.InterstitialAdListener() {
                            @Override
                            public void onError(int code, String msg) {
                                Log.e(TAG, "onError: 快手插屏" + msg);
                            }

                            @Override
                            public void onRequestResult(int adNumber) {

                            }

                            @Override
                            public void onInterstitialAdLoad(@Nullable List<KsInterstitialAd> adList) {
                                if (adList != null && adList.size() > 0) {
                                    mKsInterstitialAd = adList.get(0);
                                    KsVideoPlayConfig videoPlayConfig = new KsVideoPlayConfig.Builder()
                                            .videoSoundEnable(true)
                                            .build();
                                    if (mKsInterstitialAd != null) {
                                        mKsInterstitialAd
                                                .setAdInteractionListener(new KsInterstitialAd.AdInteractionListener() {
                                                    @Override
                                                    public void onAdClicked() {
                                                        Log.e(TAG, "onAdClicked: 点击");
                                                    }

                                                    @Override
                                                    public void onAdShow() {
                                                    }

                                                    @Override
                                                    public void onAdClosed() {
                                                    }

                                                    @Override
                                                    public void onPageDismiss() {
                                                        Log.i(TAG, "插屏广告关闭");

                                                    }

                                                    @Override
                                                    public void onVideoPlayError(int code, int extra) {
                                                        Log.e(TAG, "onVideoPlayError: " + extra);
                                                    }

                                                    @Override
                                                    public void onVideoPlayEnd() {

                                                    }

                                                    @Override
                                                    public void onVideoPlayStart() {
                                                    }

                                                    @Override
                                                    public void onSkippedAd() {

                                                    }

                                                });
                                        mKsInterstitialAd.showInterstitialAd(MainActivity.this, videoPlayConfig);
                                    }
                                }
                            }
                        });
                break;
            case "GDT":
                UnifiedInterstitialAD un = new UnifiedInterstitialAD(MainActivity.this, codeId, new UnifiedInterstitialADListener() {
                    @Override
                    public void onADReceive() {

                    }

                    @Override
                    public void onVideoCached() {

                    }

                    @Override
                    public void onNoAD(AdError adError) {
                        Log.e(TAG, "onNoAD: 广点通插屏" + adError.getErrorMsg());
                    }

                    @Override
                    public void onADOpened() {

                    }

                    @Override
                    public void onADExposure() {

                    }

                    @Override
                    public void onADClicked() {

                    }

                    @Override
                    public void onADLeftApplication() {

                    }

                    @Override
                    public void onADClosed() {

                    }

                    @Override
                    public void onRenderSuccess() {
                        Log.e(TAG, "onRenderSuccess: 加载成功");
                    }

                    @Override
                    public void onRenderFail() {

                    }
                });

                un.loadAD();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        un.show();
                    }
                }, 1000);
                break;
        }
    }

    //激励视频
    public void RewardVideoAD(String provider, String codeId) {
        switch (provider) {
            case "CSJ":
                TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(MainActivity.this);
                AdSlot adSlot = new AdSlot.Builder()
                        .setCodeId(codeId)
                        .setRewardName("金币") //奖励的名称 选填
                        .setRewardAmount(3)  //奖励的数量 选填
                        //模板广告需要设置期望个性化模板广告的大小,单位dp,激励视频场景，只要设置的值大于0即可且仅是模板渲染的代码位ID使用，非模板渲染代码位切勿使用
                        .setExpressViewAcceptedSize(500, 500)
                        .setUserID("tag123")//tag_id
                        .setMediaExtra("media_extra") //附加参数
                        .setOrientation(TTAdConstant.VERTICAL) //必填参数，期望视频的播放方向：TTAdConstant.HORIZONTAL 或 TTAdConstant.VERTICAL
                        .build();

                mTTAdNative.loadRewardVideoAd(adSlot, new TTAdNative.RewardVideoAdListener() {
                    //请求广告失败
                    @Override
                    public void onError(int code, String message) {
                        Log.e(TAG, "onError: " + message);
                        Rewardposition++;
                        if (Rewardposition>=RewardList.size()-1){
                            return;
                        }
                        RewardVideoAD(RewardList.get(Rewardposition).getProvider(),RewardList.get(Rewardposition).getId());
                    }

                    //视频广告加载后，视频资源缓存到本地的回调，在此回调后，播放本地视频，流畅不阻塞。

                    @Override
                    public void onRewardVideoCached(TTRewardVideoAd ttRewardVideoAd) {
                        Log.e(TAG, "onRewardVideoCached: 缓存到本地");
                        //开发者做一个标识
                        mIsLoaded = true;
                        ttRewardVideoAd.showRewardVideoAd(MainActivity.this, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, "scenes_test");

                    }

                    //视频广告的素材加载完毕，比如视频url等，在此回调后，可以播放在线视频，网络不好可能出现加载缓冲，影响体验。
                    @Override
                    public void onRewardVideoAdLoad(TTRewardVideoAd ad) {
                        //开发者做一个标识
                        Log.e(TAG, "onRewardVideoAdLoad: 加载播放" );
                        mIsLoaded = false;
                        ad.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
                            //广告的下载bar点击回调
                            @Override
                            public void onAdVideoBarClick() {
                                Log.e(TAG, "onAdVideoBarClick: 广告下载" );
                            }

                            //视频广告关闭回调
                            @Override
                            public void onAdClose() {
                                Log.e(TAG, "onVideoComplete: 关闭" );
                            }

                            //视频播放完成回调
                            @Override
                            public void onVideoComplete() {
                                Log.e(TAG, "onVideoComplete: 播放完成" );
                            }

                            //视频广告播放错误回调
                            @Override
                            public void onVideoError() {
                                Log.e(TAG, "onVideoError: 播放错误" );
                                Rewardposition++;
                                if (Rewardposition>=RewardList.size()-1){
                                    return;
                                }
                                RewardVideoAD(RewardList.get(Rewardposition).getProvider(),RewardList.get(Rewardposition).getId());
                            }

                            //视频播放完成后，奖励验证回调，rewardVerify：是否有效，rewardAmount：奖励梳理，rewardName：奖励名称，code：错误码，msg：错误信息
                            @Override
                            public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName, int code, String msg) {
                                webView.loadUrl("javascript:window.hbJsBridge.invokeCalback('"+callname+"',true)");
                                Log.e(TAG, "onRewardVerify: 验证奖励" );
                            }

                            //视频广告跳过回调
                            @Override
                            public void onSkippedVideo() {
                                Log.e(TAG, "onVideoComplete: 跳过" );
                            }

                            //视频广告展示回调
                            @Override
                            public void onAdShow() {
                                Log.e(TAG, "onAdShow: 激励视频展示");
                            }
                        });

                    }

                    @Override
                    public void onRewardVideoCached() {

                    }
                });
                break;
            case "KS":
                KsScene.Builder builder = new KsScene.Builder(Long.parseLong(codeId))
                        .screenOrientation(screenOrientation);

                KsScene scene = builder.build(); // 此为测试posId，请联系快手平台申请正式posId
                // 请求的期望屏幕方向传递为1，表示期望为竖屏
                KsAdSDK.getLoadManager().loadRewardVideoAd(scene, new KsLoadManager.RewardVideoAdListener() {
                    @Override
                    public void onError(int code, String msg) {
//                ToastUtil.showToast(mContext, "激励视频广告请求失败" + code + msg);
//                Log.e(TAG, "onError: " + msg);
                        Rewardposition++;
                        if (Rewardposition>=RewardList.size()-1){
                            return;
                        }
                        RewardVideoAD(RewardList.get(Rewardposition).getProvider(),RewardList.get(Rewardposition).getId());
                    }

                    @Override
                    public void onRequestResult(int adNumber) {
//                ToastUtil.showToast(mContext, "激励视频广告请求结果返回 " + adNumber);
                    }

                    @Override
                    public void onRewardVideoAdLoad(@Nullable List<KsRewardVideoAd> adList) {
                        if (adList != null && adList.size() > 0) {
                            mRewardVideoAd = adList.get(0);
                            if (mRewardVideoAd != null && mRewardVideoAd.isAdEnable()) {
                                mRewardVideoAd
                                        .setRewardAdInteractionListener(new KsRewardVideoAd.RewardAdInteractionListener() {
                                            @Override
                                            public void onAdClicked() {
//                            ToastUtil.showToast(mContext, "激励视频广告点击");
                                            }

                                            @Override
                                            public void onPageDismiss() {
//                            ToastUtil.showToast(mContext, "激励视频广告关闭");
                                                Log.e(TAG, "onVideoPlayStart: 关闭" );
                                                webView.loadUrl("javascript:window.hbJsBridge.invokeCalback('"+callname+"',true)");
                                            }

                                            @Override
                                            public void onVideoPlayError(int code, int extra) {
//                            ToastUtil.showToast(mContext, "激励视频广告播放出错");
                                                Log.e(TAG, "onVideoPlayError: " + extra + "---" + code);
                                                Rewardposition++;
                                                if (Rewardposition>=RewardList.size()-1){
                                                    return;
                                                }
                                                RewardVideoAD(RewardList.get(Rewardposition).getProvider(),RewardList.get(Rewardposition).getId());
                                            }

                                            @Override
                                            public void onVideoPlayEnd() {
//                            ToastUtil.showToast(mContext, "激励视频广告播放完成");
                                                Log.e(TAG, "onVideoPlayStart: 播放完成" );
                                            }

                                            @Override
                                            public void onVideoPlayStart() {
//                            ToastUtil.showToast(mContext, "激励视频广告播放开始");
                                                Log.e(TAG, "onVideoPlayStart: 开始" );
                                            }

                                            @Override
                                            public void onRewardVerify() {
//                            ToastUtil.showToast(mContext, "激励视频广告获取激励");
                                                Log.e(TAG, "onVideoPlayStart: 获取" );
                                            }
                                        });
                                mRewardVideoAd.showRewardVideoAd(MainActivity.this, null);
                            } else {
//            ToastUtil.showToast(mContext, "暂无可用激励视频广告，请等待缓存加载或者重新刷新");
                                Log.e(TAG, "showRewardVideoAd: 无激励视频");
                            }
                        }
                    }
                });
                break;
            case "GDT":
                RewardVideoAD rewardVideoAD = new RewardVideoAD(this, codeId, new RewardVideoADListener() {
                    @Override
                    public void onADLoad() {

                    }

                    @Override
                    public void onVideoCached() {

                    }

                    @Override
                    public void onADShow() {

                    }

                    @Override
                    public void onADExpose() {

                    }

                    @Override
                    public void onReward(Map<String, Object> map) {

                    }

                    @Override
                    public void onADClick() {

                    }

                    @Override
                    public void onVideoComplete() {

                    }

                    @Override
                    public void onADClose() {
                        webView.loadUrl("javascript:window.hbJsBridge.invokeCalback('"+callname+"',true)");
                    }

                    @Override
                    public void onError(AdError adError) {
                        Rewardposition++;
                        if (Rewardposition>=RewardList.size()-1){
                            return;
                        }
                        RewardVideoAD(RewardList.get(Rewardposition).getProvider(),RewardList.get(Rewardposition).getId());
                    }
                });// 有声播放
                rewardVideoAD.loadAD();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        rewardVideoAD.showAD();
                    }
                }, 1000);
                break;

        }
    }

    //banner广告
    public void BannerAD(String provider, String codeId) {
        switch (provider) {
            case "CSJ":
                TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(this);
                AdSlot adSlot = new AdSlot.Builder()
                        .setCodeId(codeId) //广告位id
                        .setSupportDeepLink(true)
                        .setAdCount(1) //请求广告数量为1到3条 //期望模板广告view的size,单位dp
                        .build();
                mTTAdNative.loadBannerExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
                    //请求失败回调
                    @Override
                    public void onError(int code, String message) {
                        Log.e(TAG, "onError: 穿山甲banner" + code + message);
                    }

                    //请求成功回调
                    @Override
                    public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                        Log.e(TAG, "onNativeExpressAdLoad: 请求成功" + ads.size());
                        ad = ads.get(0);
                        ad.setSlideIntervalTime(30 * 1000);
                        ad.render();
                        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
                            @Override
                            public void onAdClicked(View view, int i) {

                            }

                            @Override
                            public void onAdShow(View view, int i) {

                            }

                            @Override
                            public void onRenderFail(View view, String s, int i) {

                            }

                            @Override
                            public void onRenderSuccess(View view, float v, float v1) {
                                banner.removeAllViews();
                                banner.addView(view);
                                Log.e(TAG, "onRenderSuccess: banner展示" );
                            }
                        });
                    }
                });
                break;
            case "KS":
            case "GDT":
                UnifiedBannerView bannerView = new UnifiedBannerView(MainActivity.this, codeId, new UnifiedBannerADListener() {
                    @Override
                    public void onNoAD(AdError adError) {
                        Log.e(TAG, "onNoAD: 广点通banner"+adError );
                    }

                    @Override
                    public void onADReceive() {

                    }

                    @Override
                    public void onADExposure() {

                    }

                    @Override
                    public void onADClosed() {

                    }

                    @Override
                    public void onADClicked() {

                    }

                    @Override
                    public void onADLeftApplication() {

                    }

                    @Override
                    public void onADOpenOverlay() {

                    }

                    @Override
                    public void onADCloseOverlay() {

                    }
                });
                bannerView.loadAD();
                banner.removeAllViews();
                banner.addView(bannerView);
        }
    }



}





